<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import type { ResourceInfo } from '$lib/api/proto/resource_api';
	import type { QuestionInfo } from '$lib/api/proto/resource_exam_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import moment from 'moment';
	import ChoiceQuestionPart from './ChoiceQuestionPart.svelte';
	import EditQuestionModal from './EditQuestionModal.svelte';
	import SimpleQuestionPart from './SimpleQuestionPart.svelte';
	import TrueOrFalseQuestionPart from './TrueOrFalseQuestionPart.svelte';
	import { ChevronsLeft, EllipsisVertical } from 'lucide-svelte';
	import ConfirmModal from '$lib/components/modal/ConfirmModal.svelte';
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import {
		ChoiceQuestion,
		SimpleQuestion,
		TrueOrFalseQuestion
	} from '$lib/api/proto/resource_exam_type_api';

	const resourceId = page.url.searchParams.get('resourceId') ?? '';
	let resourceInfo: ResourceInfo | null = $state(null);

	let createIndex = $state(null as number | null);

	let questionList = $state([] as QuestionInfo[]);

	let updateQuestionInfo = $state(null as QuestionInfo | null);
	let removeQuestionInfo = $state(null as QuestionInfo | null);

	let dragQuestionInfo = $state(null as QuestionInfo | null);

	async function loadResourceInfo() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceApiClient.get({
				sessionId: userStore.userSession,
				resourceId: resourceId
			}).response
		);
		if (res.resource != undefined) {
			resourceInfo = res.resource;
		}
	}

	async function loadQuestionList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceExamApiClient.list({
				sessionId: userStore.userSession,
				resourceId: resourceId
			}).response
		);
		questionList = res.questionList;
	}

	function removeQuestionStr(): string {
		if (removeQuestionInfo == null) {
			return '';
		}
		if (removeQuestionInfo.basicInfo?.question?.typeUrl.endsWith('.ChoiceQuestion')) {
			return Any.unpack(removeQuestionInfo.basicInfo.question, ChoiceQuestion).question;
		} else if (removeQuestionInfo.basicInfo?.question?.typeUrl.endsWith('.TrueOrFalseQuestion')) {
			return Any.unpack(removeQuestionInfo.basicInfo.question, TrueOrFalseQuestion).question;
		} else if (removeQuestionInfo.basicInfo?.question?.typeUrl.endsWith('.SimpleQuestion')) {
			return Any.unpack(removeQuestionInfo.basicInfo.question, SimpleQuestion).question;
		}
		return '';
	}

	async function removeQuestion() {
		if (userStore.userSession == null || removeQuestionInfo == null) {
			return;
		}
		await callApi(
			appStore.resourceExamApiClient.remove({
				sessionId: userStore.userSession,
				resourceId: resourceId,
				questionId: removeQuestionInfo.questionId
			}).response
		);
		const tmpList = questionList.filter(
			(item) => item.questionId != removeQuestionInfo?.questionId
		);
		questionList = tmpList;
		removeQuestionInfo = null;
		appStore.addToastMessage({
			level: 'success',
			content: '删除试题成功',
			keepTime: 2000
		});
	}

	async function updateDropIndex(questionIndex: number) {
		if (userStore.userSession == null || dragQuestionInfo == null) {
			return;
		}
		await callApi(
			appStore.resourceExamApiClient.updateIndex({
				sessionId: userStore.userSession,
				resourceId: resourceId,
				questionId: dragQuestionInfo.questionId,
				questionIndex: questionIndex
			}).response
		);
		dragQuestionInfo = null;
		await loadQuestionList();
	}

	$effect(() => {
		loadResourceInfo();
	});

	$effect(() => {
		loadQuestionList();
	});
</script>

<div class="ml-[100px] mr-[100px] mt-1">
	<div class="flex justify-between border-b-2 border-base-200 h-[50px]">
		<div class="flex gap-2">
			<button type="button" class="btn btn-ghost p-1" onclick={() => goto('/app')}>
				<ChevronsLeft size="32"/>
			</button>
			<h3 class="text-3xl">
				试题库:{resourceInfo?.basicInfo?.name}
			</h3>
		</div>
		<button
			type="button"
			class="btn btn-primary"
			onclick={() => (createIndex = questionList.length)}>创建</button
		>
	</div>

	<div class="h-[calc(100vh-110px)] overflow-y-auto w-full p-2">
		{#if questionList.length == 0}
			<div class="flex flex-col items-center mt-[100px]">
				<div>试题库还是空的，请创建一些试题吧！</div>
				<button type="button" class="btn btn-primary" onclick={() => (createIndex = 0)}>创建</button
				>
			</div>
		{/if}
		{#each questionList as question, index}
			<div
				role="none"
				class="border-2 border-base-200 rounded-box"
				draggable={true}
				ondragstart={(e) => {
					dragQuestionInfo = question;
					if (e.dataTransfer != null) {
						e.dataTransfer.effectAllowed = 'move';
					}
				}}
				ondragend={() => {
					setTimeout(() => {
						dragQuestionInfo = null;
					}, 100);
				}}
			>
				<div class="flex justify-between items-center bg-base-300 rounded-box p-2 cursor-grab">
					<span
						>{index + 1}.
						{#if question.basicInfo?.question?.typeUrl.endsWith('.ChoiceQuestion')}
							选择题
						{:else if question.basicInfo?.question?.typeUrl.endsWith('.TrueOrFalseQuestion')}
							对错题
						{:else if question.basicInfo?.question?.typeUrl.endsWith('.SimpleQuestion')}
							问答题
						{/if}
					</span>
					<div class="flex gap-2 items-center">
						{moment(Number(question.createTime)).format('YYYY-MM-DD HH:mm:ss')}
						<div class="dropdown">
							<div tabindex="0" role="button" class="btn btn-ghost">
								<EllipsisVertical size={16} />
							</div>
							<ul
								class="menu dropdown-content bg-base-100 rounded-box z-1 w-[80px] p-2 shadow-sm gap-2"
							>
								<li>
									<button
										type="button"
										class="btn btn-ghost"
										onclick={() => (updateQuestionInfo = question)}>修改</button
									>
								</li>
								<li class="text-error">
									<button
										type="button"
										class="btn btn-ghost"
										onclick={() => (removeQuestionInfo = question)}>删除</button
									>
								</li>
							</ul>
						</div>
					</div>
				</div>
				{#if question.basicInfo?.question?.typeUrl.endsWith('.ChoiceQuestion')}
					<ChoiceQuestionPart question={question.basicInfo.question} />
				{:else if question.basicInfo?.question?.typeUrl.endsWith('.TrueOrFalseQuestion')}
					<TrueOrFalseQuestionPart question={question.basicInfo.question} />
				{:else if question.basicInfo?.question?.typeUrl.endsWith('.SimpleQuestion')}
					<SimpleQuestionPart question={question.basicInfo.question} />
				{/if}
			</div>
			<div
				role="none"
				class="h-[50px] rounded-box {dragQuestionInfo == null ? '' : 'bg-base-200'}"
				ondragover={(e) => {
					e.preventDefault();
					if (e.dataTransfer) {
						e.dataTransfer.effectAllowed = 'move';
					}
				}}
				ondrop={(e) => updateDropIndex(question.questionIndex + 1)}
			></div>
		{/each}
	</div>
</div>

<div class="absolute -left-[10000px]">
	{#if createIndex != null}
		<EditQuestionModal
			{resourceId}
			{createIndex}
			onCancel={() => (createIndex = null)}
			onOk={() => {
				createIndex = null;
				loadQuestionList();
			}}
		/>
	{/if}

	{#if updateQuestionInfo != null}
		<EditQuestionModal
			{resourceId}
			question={updateQuestionInfo}
			onCancel={() => (updateQuestionInfo = null)}
			onOk={() => {
				updateQuestionInfo = null;
				loadQuestionList();
			}}
		/>
	{/if}

	{#if removeQuestionInfo != null}
		<ConfirmModal
			title="删除试题"
			content={`是否删除试题${removeQuestionStr()}?`}
			okName="删除"
			type="warning"
			onCancel={() => (removeQuestionInfo = null)}
			onOk={() => removeQuestion()}
		/>
	{/if}
</div>
